import { defineStore } from "pinia"
import { gatewayStore } from "./gateway"
import { channelNameDb } from "@/local/channelNameDb" // 导入 IndexedDB 服务

interface ModuleItem {
    id: number;
    isChecked: boolean;
    status: boolean;
    deviceName: string;
    isFlashing: boolean;
    batteryLevel?: number; // 电池电量
    powerType?: 'battery' | 'wire'; // 通信类型 emun(battery,wire)
}

interface SettingItem {
    name: string;
    normal_high: number;
    normal_low: number;
    current_val: number;
}

interface Device {
    esn: string; // 设备ESN
    deviceId: string; // 设备ID
    status: boolean; // 设备在线状态
    gatewayIp: string; // 网关IP
}

export const moduleStore = defineStore("module",{
    state() {
        return {
            gateway_deviceList: new Map<string, Device[]>(),
            gatewayList: [],
            deviceList: [],
            pendingDevices: [] as string[], // 待人网的设备
            isFullscreen: false, // 是否全屏
            isOpenVoice: true, // 是否开启语音播报
            onlineDevice: [] as Device[], // 在线设备
            module_list: [] as ModuleItem[],
            current_num: 10, // 当前网关下面的数量
            module_num: 0, // 模块接入的总数
            online_num: 0, // 模块在线总数
            real_online_num: 0, // 模块实际在线总数
            selectModule: [] as ModuleItem[], // 明确类型
            isShowTip: true, // 是否有报警信息的提醒
            device_currentId: 1, // 当前设备的编号
            alarm_type: 1, 
            systemInfo: {
                diskInfo: {
                    diskPath: "c:",
                    currentPath: "C:\\Users\\user\\Desktop\\node_server",
                    diskUsage: "18.04",
                    free: "100",
                    size: "381.54"
                  },
                  memInfo: {
                      freeMem: "10940.20",
                      totalMem: "16072.73",
                      freememPercentage: "93.19"
                  },
                  cpuInfo: {
                      cpuCount: 12,
                      cpuUsage: "12.92",
                      cpuFree: "87.10",
                      platform: "12th Gen Intel(R) Core(TM) i5-12400 win32"
                  }
            },
            // 监测报警是否为同一个
            deviceStatusList: [
                new Map(), new Map(), new Map(), new Map(), new Map(),
                new Map(), new Map(), new Map(), new Map(), new Map()
            ],
            // 动态初始化阈值设置数据结构
            setting: [] as SettingItem[][]
        }
    },
    getters: {
        get_all_devices_num: (state) => {
            const gateway_store = gatewayStore();
            const gatewayList = gateway_store.gatewayList;
            const deviceList: Device[] = [];
            const onlineDevice: Device[] = [];
            for (const gateway of gatewayList) {
                const devices = state.gateway_deviceList.get(gateway.ip) || [];
                deviceList.push(...devices);
                const onlineDevices = devices.filter(device => device.status === true);
                onlineDevice.push(...onlineDevices);
            }
            console.log('获取所有设备数量',deviceList)
            console.log('获取所有在线设备数量',onlineDevice)
            state.onlineDevice = onlineDevice;
            state.online_num = onlineDevice.length;
            return deviceList.length;
        },
    },
    actions: {
        updateDeviceCounts() {
            const gateway_store = gatewayStore();
            const gatewayList = gateway_store.gatewayList;
            const deviceList: Device[] = [];
            const onlineDevice: Device[] = [];
            for (const gateway of gatewayList) {
                const devices = this.gateway_deviceList.get(gateway.ip) || [];
                deviceList.push(...devices);
                const onlineDevices = devices.filter(device => device.status === true);
                onlineDevice.push(...onlineDevices);
            }
            this.onlineDevice = onlineDevice;
            this.online_num = onlineDevice.length;
            this.module_num = deviceList.length;
        },
        // 设置待人网的设备
        setPendingDevices(devices: Device[]) {
            console.log('🔍 [DEBUG] setPendingDevices 接收到的数据:', devices)
            
            // 提取新设备的ESN列表
            const newEsns = devices.map(item => {
                console.log('🔍 [DEBUG] 处理设备项:', item)
                return item.esn
            })
            
            // 过滤掉已存在的ESN，防止重复添加
            const uniqueEsns = newEsns.filter(esn => {
                const exists = this.pendingDevices.includes(esn)
                if (exists) {
                    console.log('🔍 [DEBUG] ESN已存在，跳过添加:', esn)
                }
                return !exists
            })
            
            // 将不重复的ESN添加到待入网设备列表
            this.pendingDevices.push(...uniqueEsns)
            
            console.log('🔍 [DEBUG] 新增的ESN:', uniqueEsns)
            console.log('🔍 [DEBUG] 设置后的pendingDevices数组:', this.pendingDevices)
        },
        // 获取随机的待人网的设备
        getRandomPendingDevice(): string | null {
            console.log('🔍 [DEBUG] getRandomPendingDevice 被调用')
            console.log('🔍 [DEBUG] 当前pendingDevices:', this.pendingDevices)
            console.log('🔍 [DEBUG] pendingDevices长度:', this.pendingDevices.length)
            
            if (this.pendingDevices.length === 0) {
                console.log('🔍 [DEBUG] pendingDevices为空，返回null')
                return null
            }
            
            const randomIndex = Math.floor(Math.random() * this.pendingDevices.length)
            const selectedDevice = this.pendingDevices[randomIndex]
            console.log('🔍 [DEBUG] 随机索引:', randomIndex)
            console.log('🔍 [DEBUG] 选中的设备ESN:', selectedDevice)
            
            return selectedDevice
        },
        removePendingDevice(esn: string): boolean {
            const index = this.pendingDevices.findIndex(device => device === esn)
            if (index !== -1) {
                this.pendingDevices.splice(index, 1)
                return true
            }
            return false
        },
        // 添加设备ESN到待入网设备列表
        addPendingDevice(esn: string): boolean {
            // 检查ESN是否已存在，避免重复添加
            if (!this.pendingDevices.includes(esn)) {
                this.pendingDevices.push(esn)
                console.log('🔍 [DEBUG] 成功添加ESN到待入网设备列表:', esn)
                console.log('🔍 [DEBUG] 当前待入网设备列表:', this.pendingDevices)
                return true
            } else {
                console.log('🔍 [DEBUG] ESN已存在于待入网设备列表中:', esn)
                return false
            }
        },
        setDevice(devices: Device[]) {
            console.log('🔍 [DEBUG] setDevice 接收到的数据:', devices)
           for(let device of devices){
             if (this.gateway_deviceList.has(device.gatewayIp)) {
                // 同一个网关下面只能有一个相同的ESN
                const existingDevice:Device | undefined = this.gateway_deviceList.get(device.gatewayIp)?.find(item => item.esn === device.esn)

                // 还有一种如果状态时一样的也不需要存储，如果状态不一样进行更改
                if (existingDevice && existingDevice.status === device.status) {
                    console.log('🔍 [DEBUG] 网关IP为', device.gatewayIp, '的设备列表中ESN为', device.esn, '的设备状态与新状态相同，无需更新')
                    continue
                }

                if (existingDevice) {
                    existingDevice.status = device.status
                    this.gateway_deviceList.get(device.gatewayIp)?.push(existingDevice)
                    continue
                }

                // 设备不存在直接进行添加
                this.gateway_deviceList.get(device.gatewayIp)?.push(device)
                
                console.log('🔍 [DEBUG] 网关IP为', device.gatewayIp, '的设备列表中ESN为', device.esn, '的设备状态已更新为', device.status)
             } else {
                this.gateway_deviceList.set(device.gatewayIp, [device])
             }
           }
           console.log('🔍 [DEBUG] 初始化网关设备列表:', this.gateway_deviceList)
        },
        async getAllDevices(): Promise<Device[]> {
            const gateway_store = gatewayStore();
            const gatewayList = gateway_store.gatewayList;
            const deviceList: Device[] = [];
            for (const gateway of gatewayList) {
                const devices = this.gateway_deviceList.get(gateway.ip) || [];
                deviceList.push(...devices);
            }
            return deviceList;
        },
        // 获取网关设备的数量
        getGatewayNumber(gatewayIp: string): number {
            const devices = this.gateway_deviceList.get(gatewayIp) || [];
            return devices.length
        },
        // 根据网关ID获取模块列表
        async getModuleList(gatewayId: number,currentIp?: string) {
            const gateway_store = gatewayStore();
            const currentGatewayId = gatewayId ?? gateway_store.activeGatewayId;
            const gatewayIp = currentIp ?? gateway_store.currentIp;
            console.log(currentGatewayId, 'gatewayIp:', gatewayIp)
            // 1. 从 IndexedDB 加载所有自定义名称
            const customNames = await channelNameDb.getAllNames();

            // 2. 生成基础模块列表（模拟数据）
            this.module_list = [] // 清空 module_list
            this.selectModule = [] // 清空 selectModule
            this.setting = [] // 清空设置数据

            // 创建设备模块
            const deviceNum: number = Math.ceil(this.current_num / 10) * 10;

            for (let i = 0; i < deviceNum ; i++) {
                const moduleId = i + 1;
                const dbKey = `${gatewayIp}-${moduleId}`;
                const customName = customNames.get(dbKey);

                const newModule: ModuleItem = {
                    id: moduleId,
                    isChecked: i === 0, // 默认选中第一个
                    status: true,
                    // 如果有自定义名称，则使用它，否则使用默认名称
                    deviceName: customName || `监测点 ${moduleId}`,
                    isFlashing: false
                };
                this.module_list.push(newModule);
                this.selectModule.push(newModule);

                // 为每个模块初始化默认阈值设置
                this.setting.push([
                    { name: "紫外", normal_high: 30000, normal_low: 100, current_val: 1500 },
                    { name: "红外", normal_high: 100, normal_low: 0, current_val: 50 },
                    { name: "温度", normal_high: 100, normal_low: 0, current_val: 50 },
                    { name: "湿度", normal_high: 100, normal_low: 0, current_val: 70 },
                    { name: "压力", normal_high: 200, normal_low: 0, current_val: 121 }
                ]);
            }
            // 如果列表不为空，则更新当前选中的设备ID
            if (this.selectModule.length > 0) {
                this.device_currentId = this.selectModule[0].id;
            }
            
        },
        
        /**
         * 更新通道（监测点）的名称
         * @param gatewayId - 当前网关ID
         * @param moduleId - 要更新的模块ID
         * @param newName - 新的自定义名称
         */
        async updateChannelName(gatewayId: number, moduleId: number, newName: string) {
            console.log(gatewayId, moduleId, newName)
            const gateway_store = gatewayStore();
            // 1. 更新 Pinia state 中的名称
            const moduleToUpdate = this.selectModule.find(m => m.id === moduleId);
            if (moduleToUpdate) {
                moduleToUpdate.deviceName = newName;
                console.log(`State updated for module ${moduleId} to name "${newName}"`);
            }

            // 2. 将新名称持久化到 IndexedDB，使用网关IP而不是ID
            const gatewayIp = gateway_store.currentIp;
            await channelNameDb.saveName(gatewayIp, moduleId, newName);
        },

        // 修改阈值
        changeValue(option: { id: number, currentValue: number | undefined }) {
            if (option.currentValue !== undefined) {
                this.setting[0][option.id].current_val = option.currentValue
            }
        }
    },
})